//
//  BSDeptTreeResultView.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/12/7.
//

import Foundation
import UIKit

class BSDeptTreeResultView: UIView {
    let headerV = BSSearchBar(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 60))
    let treeTable = BSDeptTreeTable(withSubExpand: true)

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        NotificationCenter.default.addObserver(self, selector: #selector(textFiledEditChanged), name: UITextField.textDidChangeNotification, object: headerV.searchTF)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func resetUI() {
        treeTable.datas = []
        headerV.searchTF.text = ""
        headerV.searchTF.becomeFirstResponder()
    }
    
    func reloadData(withVal val: String) {
        showToastActivity()
        API.getDeptTree(withParam: DeptParam(deptName: val), block: { responseModel in
            DispatchQueue.main.async {
                self.treeTable.datas = responseModel.models ?? []
                self.hideToastActivity()
            }
        })
    }
    
    @objc func textFiledEditChanged() {
        let value = headerV.searchTF.text
        
        if value == nil || value == "" {
            self.treeTable.datas = []
        } else {
            self.treeTable.datas.removeAll()
            reloadData(withVal: value ?? "")
        }
    }
    
    func setupUI() {
        headerV.searchTF.placeholder = "搜索网点"
        headerV.padding = 25
        addSubview(headerV)
        headerV.snp.makeConstraints { (make) in
            make.top.centerX.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(60)
        }
        
        addSubview(treeTable)
        treeTable.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(headerV.snp.bottom)
        }
    }
}
